package com.ftg.learn.rbac.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.ftg.learn.rbac.entity.Permission;
import com.ftg.learn.rbac.entity.User;
import com.ftg.learn.rbac.mapper.UserMapper;
import com.ftg.learn.rbac.service.IUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpSession;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.*;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author kangjx
 * @since 2022-03-23
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

    @Override
    public Map<String,Object> checkUser(String account, String password,HttpSession session) {
        Map<String,Object> map = new HashMap<>();
        if(null == account||"".equalsIgnoreCase(account)){
            map.put("mess","用户名不能为空");
            return map;
        }else if(null == password||"".equalsIgnoreCase(password)){
            map.put("mess","密码不能为空");
            return map;
        }else{
            byte[] bs1 = new byte[0];
            try {
                bs1 = MessageDigest.getInstance("md5").digest(password.getBytes());
                password = new BigInteger(1, bs1).toString(16);
            } catch (NoSuchAlgorithmException e) {
                e.printStackTrace();
            }
            //password 就是加密以后的密文
            User user = super.baseMapper.checkUser(account,password);
            if(Objects.isNull(user)){
                map.put("mess","当前用户不存在!!!");
                return map;
            }else{
//                //我想把当前用户存储起来  session  客户端与服务端 私有缓存
//                session.setAttribute("userName",user.getUname());
//                session.setAttribute("userId",user.getUid());
                map.put("mess","登陆成功!!!");
                session.setAttribute("uid",user.getUid());
                session.setAttribute("username",user.getUname());
                return map;
            }
        }
    }

    @Override
    public boolean saveForPassword(User e) {
        byte[] bs1 = new byte[0];
        try {
            bs1 = MessageDigest.getInstance("md5").digest(e.getUpassword().getBytes());
            e.setUpassword(new BigInteger(1, bs1).toString(16));
        } catch (NoSuchAlgorithmException e1) {
            e1.printStackTrace();
        }
        QueryWrapper<User> query = new QueryWrapper<>();
        query.eq("uaccount",e.getUaccount());
        User user = this.baseMapper.selectOne(query);
        if(Objects.isNull(user)){
            return this.baseMapper.insert(e) >= 0 ? true : false;
        }
        return false;
    }

    @Override
    public boolean updateIce(int id,int num) {
        int sum = super.baseMapper.updateForUstatus(id,num);
        return  sum >= 0 ? true : false;
    }

    @Override
    public boolean updateUserInfo(int uid, String uaccount, String uname) {
        return super.baseMapper.updateUserInfo(uid,uaccount,uname);
    }

    @Override
    public boolean resetPassword(int uid) {
        String newPass = "88888888";
        byte[] bs1;
        try {
            bs1 = MessageDigest.getInstance("md5").digest(newPass.getBytes());
            newPass = new BigInteger(1, bs1).toString(16);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return super.baseMapper.resetPassword(uid,newPass);
    }

    /**
     * 获得当前某个的全部角色
     * @param uid 当前用户的编号
     * @return
     */
    @Override
    public String logedByPermssion(Integer uid) {

        List<Permission> list = super.baseMapper.allPermissionByUid(uid);
        //转换...把当前方法的给的list 转换成一颗树
        try {
            return this.parsePermissionWithTree(list, DEFAULT_PARENT_ID).toString();
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return "[]";
    }

    /**
     * 默认的全局最大的结点 父id
     */
    private final int DEFAULT_PARENT_ID = -1;

    /**
     * 转换功能
     * @param list  全部角色
     * @param begin 最上级的角色 parentid
     */
    private JSONArray parsePermissionWithTree(List<Permission> list, int begin) throws JSONException {
        JSONArray rearr = new JSONArray();
        if(Objects.isNull(list) && list.size() == 0){
            return rearr;
        }
        for (int i = 0; i < list.size(); i++) {
            Permission p = list.get(i);
            if(!Objects.isNull(p) && p.getParentId() == begin){
                JSONObject reobj = new JSONObject();
                reobj.put("title",p.getTitle());
                reobj.put("icon",p.getIcon());
                reobj.put("href",p.getAction());
                reobj.put("target","_self");

                reobj.put("child",parsePermissionWithTree(list, p.getId()));
                rearr.put(reobj);
            }
        }
        return rearr;
    }

}
